<?php
namespace app\zb\controller;
use think\Controller;
use think\Db;
use think\Exception;
use think\Loader;
use think\Session;
use think\View;

class Upload extends Controller
{
    /*
     * stdClass Object转array
     * */
    function object2array(&$object) {
        $object =  json_decode( json_encode( $object),true);
        return  $object;
    }
    /**
     *      把秒数转换为时分秒的格式
     *      @param Int $times 时间，单位 秒
     *      @return String
     */
    function dataformat($times) {
        $hour = floor($times/3600);
        if($hour == 0 || $hour < 10){
            $hour = '0'.$hour;
        }
        $minute = floor(($times-3600*$hour)/60);
        if($minute == 0 || $minute < 10){
            $minute = '0'.$minute;
        }
        $second = floor((($times-3600*$hour)-60*$minute)%60);
        if($second == 0 || $second < 10){
            $second = '0'.$second;
        }
        return $hour.':'.$minute.':'.$second;
    }
    /*
     * 视频上传
     * */
    function index(){
        @$setTitle = $_POST['setTitle'];
        @$description = $_POST['description'];
        @$tag = $_POST['tag'];
        @$img_address = $_POST['img_address'];
        if($setTitle == '' || $description == '' || $tag == '' || $img_address == '' ){
            return view();
        }else{
            Loader::import('AliyunOpenapiPhpSdkMaster.aliyun-php-sdk-core.Config');
            Loader::import('AliyunOpenapiPhpSdkMaster.aliyun-php-sdk-core.Regions.EndpointConfig');
            Loader::import('AliyunOpenapiPhpSdkMaster.aliyun-php-sdk-core.DefaultAcsClient');
            $regionId = 'cn-shanghai';
            $profile = \DefaultProfile::getProfile($regionId, 'LTAI4JFTraQjomTV', 'jXR9FpGrrnJt08YHdnzaOmhDiG2Nj8');
            $client = new \DefaultAcsClient($profile);

            $request = new \vod\Request\V20170321\CreateUploadVideoRequest();
            $request->setAcceptFormat('JSON');
            $request->setRegionId($regionId);
            $request->setTitle($setTitle);
            //视频源文件名称(必须包含扩展名)
            $request->setFileName("video.mp4");
            $request->setTags($tag);
            $request->setDescription($description);
            //自定义视频封面URL地址
            $request->setCoverURL($img_address);
            $response = $client->getAcsResponse($request);

            $info = $this->object2array($response);
            $data['uploadAuth'] = $info['UploadAuth'];
            $data['uploadAddress'] = $info['UploadAddress'];
            $data['videoId'] = $info['VideoId'];

            return  json(['code' => 1,  'msg' => $data]);
        }
    }
    /*
     * 封面图上传处理
     * */
    public function upload_img()
    {
        if($_FILES['fb_img']['tmp_name']){
            $pic = $this ->request ->file('fb_img');
            $info = $pic -> move(ROOT_PATH . 'public/uploads/video_cover');
            if($info){
                $img = '/uploads/video_cover/' .$info->getSaveName();//此路径用于图片处理（缩放填充）
                $image = \think\Image::open('.'.$img);
                $image->thumb(138,80,\think\Image::THUMB_FILLED)->save('.'.$img);

                $url = $_SERVER['HTTP_HOST'];
                $file = str_replace('\\','/',$info->getSaveName());
                $pic = 'http://'. $url . '/uploads/video_cover/' .$file;
                return $pic;exit;
            }else{
                return false;exit;
            }
        }
    }
    /*
     * 获取上传视频信息
     * */
    function getPlayInfo($videoId) {
        Loader::import('AliyunOpenapiPhpSdkMaster.aliyun-php-sdk-core.Config');
        Loader::import('AliyunOpenapiPhpSdkMaster.aliyun-php-sdk-core.DefaultAcsClient');
        $regionId = 'cn-shanghai';
        $profile = \DefaultProfile::getProfile($regionId, 'LTAI4JFTraQjomTV', 'jXR9FpGrrnJt08YHdnzaOmhDiG2Nj8');
        $client = new \DefaultAcsClient($profile);
        $request = new \vod\Request\V20170321\GetPlayInfoRequest();

        $request->setVideoId($videoId); // 准备播放的视频ID
        $request->setFormats("mp4");
        $request->setAuthTimeout("1800");

        $response = $client->getAcsResponse($request);

        $info = $this->object2array($response);

        return $info;
	}
    /*
     * 视频转码完成的回调地址
     * 视频信息入库
     * */
    public function TranscodingCallBack(){
        $VideoId = $_POST['VideoId'];//视频id

        $videoInfo = $this->getPlayInfo($VideoId);
        foreach($videoInfo['PlayInfoList']['PlayInfo'] as $k => $v){
            //获取文件名
            $fileName = basename($v['PlayURL']);
            //获取文件后缀名
            $fileEx = strtolower(substr(strrchr($fileName,"."),1));
            if($fileEx == 'mp4' && $v['Definition'] == 'SD'){
                $info['name'] = $videoInfo['VideoBase']['Title'];//视频标题
                $info['image'] = $videoInfo['VideoBase']['CoverURL'];//封面图片
                $info['url'] = $v['PlayURL'];//mp4高清视频播放地址
                $info['duration'] = $this->dataformat(floor($v['Duration']));//播放时长

                model('zb_video')->save($info);//上传视频信息入库
            }
        }
    }

    /*
     * 媒体转码sdk
     * step1 搜索管道（获取管道id）
     * step2
     * */
    public $pipeline_id;
    function getPipeline(){
        Loader::import('AliyunOpenapiPhpSdkMaster.aliyun-php-sdk-core.Config');
        Loader::import('AliyunOpenapiPhpSdkMaster.aliyun-php-sdk-core.DefaultAcsClient');
        $regionId = 'cn-shanghai';
        $profile = \DefaultProfile::getProfile($regionId, 'LTAI4JFTraQjomTV', 'jXR9FpGrrnJt08YHdnzaOmhDiG2Nj8');

        $client = new \DefaultAcsClient($profile);
        $request = new Mts\SearchPipelineRequest();
        // 如果出错，可能会抛出ClientException或ServerException异常
        $response = $client->getAcsResponse($request);
        $pipelines = $response->PipelineList->Pipeline;

        foreach ($pipelines as $pipeline) {
            return $pipeline_id = $pipeline->Id;
//            echo 'pipeline id:' . $pipeline->Id . ', name:' . $pipeline->Name . ', state:' . $pipeline->State . "\n";
        }
    }

}